//
//  ProvinceSelectViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-8-23.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "ProvinceSelectViewController.h"
#import "Helper.h"
#import "Config.h"

//  -业务逻辑细节说明-
//
//  @abstract       显示出某个区域下，所有的一级省市以及对应的省市下被选中的二级城市。

//  @discussion     webview加载完成后，先会显示出所有的二级城市，然后根据上级VC是否传入了要默认勾选的或显示的城市信息进行二次渲染（即是否在用户修改的时候，要显示出用户以前选择过的）。
//                  用户选择过二级城市后，会同时体现在当前webview上。

//  @notes          需要将选择后的最终数据传递给上级页面或者需要对比修改前后的数据时，始终都通过JS获取HTML显示的城市数据，这样可以简化数据操作。


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

@interface ProvinceSelectViewController ()

@end

@implementation ProvinceSelectViewController
@synthesize delegate = _delegate;
@synthesize currentProvinces = _currentProvinces;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithProvinces:(NSArray *)provinces
{
    self = [super init];
    if (self) {
        _provincesInArea = provinces;
        
        _provincesSelected = [NSMutableArray new];
        
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //返回按钮
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    //保存
    UIButton *saveButton = [Helper buttonWithStyle:ButtonStyleNavigationSave];
    [saveButton addTarget:self action:@selector(saveButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"select_province" ofType:@"html"];
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT-44.0f)];
    _webView.delegate = self;
    
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
    [self.view addSubview:_webView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 私有方法

//根据HTML的返回情况，组装服务器所需要的数据
//HTML返回的结果有三种情况：
//1、@“all”,表示的一级省市下所有的二级城市都被勾选
//2、@"",表示此一级省市下所有的二级城市都没有被勾选
//3、最后一种情况，表示一级省市下所有的二级城市部分被选中
- (NSDictionary *)provinceSelected:(NSString *)province
{
    NSDictionary *provinceSelected;
    
    NSString *result = [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"select_result('%@')",province]];
    
    //获取该省下被选中的二级城市信息
    
    if ([result isEqualToString:@"all"]) {
        
        //如果该省被全选,就获取所有的二级城市
        for (NSDictionary *tempProvince in _provincesInArea) {
            
            if ([tempProvince[@"name"] isEqualToString:province]) {
                
                NSMutableArray *cities = [NSMutableArray new];
                
                
                for (NSDictionary *city in tempProvince[@"cities"]) {
                    
                    [cities addObject:city[@"name"]];
                }
                provinceSelected = [NSDictionary dictionaryWithObjectsAndKeys:
                                    province, @"province",
                                    [cities componentsJoinedByString:@","], @"city",
                                    [NSNumber numberWithInteger:[cities count]], @"cityNum",
                                    self.title, @"anArea", nil];
                break;

            }
        }
        
    }
    else if ([result isEqualToString:@""]) {
        
        
    }
    
    //HTML返回的是以“，”隔开的二级城市的字符串
    else {
        
        NSArray *cities = [result componentsSeparatedByString:@","];
        
        provinceSelected = [NSDictionary dictionaryWithObjectsAndKeys:
                            province, @"province",
                            result, @"city",
                            [NSNumber numberWithInteger:[cities count]], @"cityNum",
                            self.title, @"anArea", nil];
        
        
    }
    
    return provinceSelected;
}

//从HTML中获取一次当前被选中的省市信息
- (void)currentProvincesArray
{
    if (_provincesSelected.count != 0) {
        [_provincesSelected removeAllObjects];
    }
    
    for (NSDictionary *tempProvince in _provincesInArea) {
        
        NSDictionary *province = [self provinceSelected:tempProvince[@"name"]];
        
        if (province != nil) {
            [_provincesSelected addObject:province];
        }
    }
}

#pragma mark - 事件

- (void)backButtonEvent:(id)sender
{
    [self currentProvincesArray];
    
    if ([_provincesSelected isEqualToArray:_currentProvinces]) {
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_123") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        alertView.tag = 1;
        [alertView show];
    }
}

- (void)saveButtonEvent:(id)sender
{

    [self currentProvincesArray];

    if ([_delegate respondsToSelector:@selector(provincesSelected:inWhichArea:)]) {
        
        NSString *area = self.title;
        
        [_delegate provincesSelected:_provincesSelected inWhichArea:area];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIWebView Delegate

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //初始化当前区域下的所有省市数据
    if (_provincesInArea == nil || _provincesInArea.count == 0) {
        return;
    }
    
    //拼接javascript语法的数组字符串，传递给HTML
    NSString *str = @"var provinces = new Array(";
    
    //解析字符串
    for (int i = 0; i<_provincesInArea.count; i++) {
        
        if (i != 0) {
            str = [str stringByAppendingString:@","];
        }
        str = [str stringByAppendingFormat:@"'%@'",_provincesInArea[i][@"name"]];
    }
    
    str = [str stringByAppendingString:@")"];
    
    [_webView stringByEvaluatingJavaScriptFromString:str];
    [_webView stringByEvaluatingJavaScriptFromString:@"show();"];
    
    
    //初始化完成后，如果_currentProvinces不为nil，说明从前面的页面中，传过来了要显示的省市数据，将其显示出来
    if (_currentProvinces != nil) {
        
        [_provincesSelected addObjectsFromArray:_currentProvinces];

        //如果前面是勾选的整个区域，那么就全部勾选一级省市
        if (_provincesSelected.count != 0 && [_provincesSelected[0] isKindOfClass:[NSString class]] && [_provincesSelected[0] isEqualToString:@"all"]) {
            for (int i=0; i<_provincesInArea.count; i++) {
                [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"cities_selected(%d, '%@');",i,@"all"]];

            }
            return;
        }
        
        //设置被选过的一级省市
        //设置每一个被选过的一级省市下的二级城市列表
        
        for (NSDictionary *province in _provincesSelected) {
            
            //找到需要设置的一级省市的索引
            NSInteger provinceIndex;
            
            for (int i=0; i<_provincesInArea.count; i++) {
                if ([province[@"province"] isEqualToString:_provincesInArea[i][@"name"] ]) {
                    provinceIndex = i;
                }
            }
            
            //拼凑需要显示的二级城市的列表字符串
            //拼接字符串
            
            //需要显示的二级城市的名称集合
            NSArray *cityIdArray = [province[@"city"] componentsSeparatedByString:@","];
            
            //传递给JS的二级城市名称的集合
            NSString *citiesString = @"";
            
            //如果需要显示的省市的二级城市和该省市的二级城市的个数一样，就代表全选
            if (cityIdArray.count == [_provincesInArea[provinceIndex][@"cities"] count]) {
                
                citiesString = @"all";
            }
            else {
                
                citiesString = province[@"city"];
            }
            
            [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"cities_selected(%d, '%@');",provinceIndex,citiesString]];
        }
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    NSArray *cityArray = [request.URL.relativeString componentsSeparatedByString:@"?"];
    
    if ([cityArray[0] isEqualToString:@"open:select_city"]) {
        
        if (cityArray.count == 2) {

            _indexSelected = [cityArray[1] integerValue];
            
            CitySelectViewController *citySelectVC = [[CitySelectViewController alloc] initWithProvince:_provincesInArea[[cityArray[1] integerValue]]];
            
            citySelectVC.title = _provincesInArea[_indexSelected][@"name"];
            citySelectVC.delegate = self;
            citySelectVC.currentCities = [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"select_result('%@')",_provincesInArea[_indexSelected][@"name"]]];         
            [self.navigationController pushViewController:citySelectVC animated:YES];
        }
    }
    return  YES;
}

#pragma mark - CitySelectedDelegate

- (void)citiesDidSelected:(NSString *)cities inProvince:(NSString *)province
{
    //将修改后的显示出来
    //需要显示的二级城市的名称集合
    NSArray *cityIdArray = [cities componentsSeparatedByString:@","];
    
    //传递给JS的二级城市名称的集合
    NSString *citiesString = @"";
    
    //找到需要设置的一级省市的索引
    NSInteger provinceIndex;
    
    for (int i=0; i<_provincesInArea.count; i++) {
        if ([province isEqualToString:_provincesInArea[i][@"name"] ]) {
            provinceIndex = i;
        }
    }
    
    //如果需要显示的省市的二级城市和该省市的二级城市的个数一样，就代表全选
    if (cityIdArray.count == [_provincesInArea[provinceIndex][@"cities"] count]) {
        
        citiesString = @"all";
    }
    else {
        
        citiesString = cities;
    }
    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"cities_selected(%d, '%@');",provinceIndex,citiesString]];
//    
//    NSDictionary *provinceSelected;
//    
//    if (cities.length != 0) {
//        
//        //选择一次二级城市，就生成一次被选中的省市对象，并添加到被选中的省市对象集合中
//        provinceSelected = [NSDictionary dictionaryWithObjectsAndKeys:
//                                          province, @"province",
//                                          cities, @"city",
//                                          [NSNumber numberWithInteger:[[cities componentsSeparatedByString:@","] count]], @"cityNum",
//                                          self.title, @"anArea", nil];
//    }
//    
//    //先去判断此省市是否以前被添加过，是则替换，无则添加
//    if (_provincesSelected.count != 0) {
//        
//        BOOL flag = NO;
//        NSInteger indexAdded;
//        
//        //查找是否被添加过
//        for (int i=0; i<_provincesSelected.count; i++) {
//            
//            if ([_provincesSelected[i][@"province"] isEqualToString:province]) {
//                
//                flag = YES;
//                indexAdded = i;
//            }
//        }
//        
//        //是
//        if (flag) {
//            
//            //如果二级城市一个未勾选，就清除此对象
//            if (cities.length == 0) {
//                [_provincesSelected removeObjectAtIndex:indexAdded];
//            }
//            else {
//                
//                [_provincesSelected replaceObjectAtIndex:indexAdded withObject:provinceSelected];
//            }
//        }
//        //否
//        else {
//            
//            //如果二级城市一个未勾选就什么也不做
//            if (cities.length != 0) {
//                [_provincesSelected addObject:provinceSelected];
//            }
//        }
//    }
//    else {
//        
//        //如果二级城市一个未勾选就什么也不做
//        if (cities.length != 0) {
//            [_provincesSelected addObject:provinceSelected];
//        }
//    }
}

////在一级城市的右边显示所有被选中的二级城市
//- (void)showCitiesSelected:(NSDictionary *)province
//{
//    
//    //获得要显示的二级城市列表的索引集合
//    NSArray *cityIdArray = [(NSString *)_citiesSelectedInProvince[_indexSelected] componentsSeparatedByString:@","];
//
//    NSArray *cities = province[@"cities"];
//    
//    //拼接字符串
//    NSString *citiesString = @"";
//    
//    if ([cityIdArray[0] isEqualToString:@""]) {
//    
//    }else if ([cityIdArray[0] isEqualToString:@"all"]) {
//        citiesString = @"all";
//    }else {
//        for (int i=0; i<cityIdArray.count; i++) {
//            
//            if (i != 0) {
//                
//                [citiesString stringByAppendingString:@","];
//            }
//            
//            NSInteger index = [cityIdArray[i] integerValue];
//            
//            citiesString = [citiesString stringByAppendingString:cities[index][@"name"]];
//        }
//
//    }
//    
//    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"cities_selected(%d, '%@');",_indexSelected,citiesString]];
//}
#pragma mark - UIAlerView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1) {
        if (buttonIndex == 1) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}
@end
